package com.scau402.system1.domain.factory;

import com.scau402.system1.domain.po.WmsWarehouseDO;
import com.scau402.system1.domain.po.WmsWarehouseStoragePO;
import com.scau402.system1.domain.bo.WmsWarehouseBO;
import com.scau402.system1.domain.bo.WmsWarehouseStorageBO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 仓库实体工厂类
 *
 * @author
 * @create 2024/1/3 18:38
 * @description
 */
@Component
public class WmsWarehouseFactory {

    public List<WmsWarehouseBO> toWmsWarehouseBOList(List<WmsWarehouseDO> wmsWarehouseDOPOList,
                                                            Map<Long, List<WmsWarehouseStoragePO>> wmsWarehouseStorageMap) {
        return Optional.ofNullable(wmsWarehouseDOPOList)
                .orElse(new ArrayList<>(0))
                .stream()
                .map(po -> toWmsWarehouseBO(po, wmsWarehouseStorageMap.computeIfAbsent(po.getId(), k -> new ArrayList<>(0))))
                .collect(Collectors.toList());
    }

    private WmsWarehouseBO toWmsWarehouseBO(WmsWarehouseDO wmsWarehouseDOPO, List<WmsWarehouseStoragePO> wmsWarehouseStorageDOPOList) {
        return Optional.ofNullable(wmsWarehouseDOPO)
                .map(x -> {
                    WmsWarehouseBO wmsWarehouseBO = new WmsWarehouseBO();
                    BeanUtils.copyProperties(x, wmsWarehouseBO);
                    wmsWarehouseBO.setStorageMap(toWmsWarehouseStorageMap(wmsWarehouseStorageDOPOList));
                    return wmsWarehouseBO;
                })
                .orElse(null);
    }

    private Map<Long, WmsWarehouseStorageBO> toWmsWarehouseStorageMap(List<WmsWarehouseStoragePO> wmsWarehouseStorageDOPOList) {
        return Optional.ofNullable(wmsWarehouseStorageDOPOList)
                .orElse(new ArrayList<>(0))
                .stream()
                .collect(Collectors.toMap(WmsWarehouseStoragePO::getId, this::toWmsWarehouseStorageBO));
    }

    private WmsWarehouseStorageBO toWmsWarehouseStorageBO(WmsWarehouseStoragePO po) {
        return Optional.ofNullable(po)
                .map(x -> {
                    WmsWarehouseStorageBO wmsWarehouseStorageBO = new WmsWarehouseStorageBO();
                    BeanUtils.copyProperties(x, wmsWarehouseStorageBO);
                    return wmsWarehouseStorageBO;
                })
                .orElse(null);
    }

}
